package com.arrake.controller;

import com.arrake.dao.WebFileDao;
import com.arrake.pojo.PageResult;
import com.arrake.pojo.QueryPageBean;
import com.arrake.pojo.Result;
import com.arrake.pojo.WebFile;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * description!TODO
 *
 * @author Arrake
 * @email arrake@111.com
 * @date 2021/5/11
 */
@Controller
public class FileController {

    @Autowired
    private WebFileDao webFileDao;
    @GetMapping("/")
    public String upload(){
        return "upload";
    }

    // 向文件上传页面跳转
    @GetMapping("/toUpload")
    public String toUpload(){
        return "upload";
    }

    // 文件上传管理
    @PostMapping("/uploadFile")
    @ResponseBody
    public Result uploadFile(@RequestParam("file")MultipartFile file,HttpServletRequest request) {
        WebFile webFile = new WebFile();
        // 获取文件名以及后缀名
            String fileName = file.getOriginalFilename();
            webFile.setFileName(fileName);

        String[] split = fileName.split("\\.");

        if (split.length!=0){
            webFile.setType(split[split.length-1]);
        }else {
            webFile.setType("blob");
        }

        // 重新生成文件名（根据具体情况生成对应文件名）
            UUID id = UUID.randomUUID();

            webFile.setId(id+"");

            //这样可以通过肉眼查找文件
            fileName = id +"_"+fileName;
            // 指定上传文件本地存储目录，不存在需要提前创建

            String dirPath = "src/main/resources/static/resource";

            File filePath = new File(dirPath);
            if(!filePath.exists()){
                filePath.mkdirs();
            }

        String remoteAddr = request.getRemoteAddr();
        webFile.setIp(remoteAddr);


        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


        //注意separator
            try {
                //存的时候用绝对路径
                file.transferTo(new File(filePath.getAbsolutePath()+File.separator+fileName));
                webFile.setPath(filePath.getPath()+'/'+fileName);
                webFile.setCreateTime(simpleDateFormat.format(new Date()));
                webFileDao.addWebFile(webFile);
                return new Result(true, "上传成功", webFile);
            } catch (Exception e) {
                e.printStackTrace();
                // 上传失败，返回失败信息
                System.out.println(e.getMessage());
               return new Result(false, "上传失败");
            }
        // 携带上传状态信息回调到文件上传页面
    }



    // 所有类型文件下载管理
    @PostMapping("/download")
    public ResponseEntity<byte[]> fileDownload(HttpServletRequest request) throws Exception{
        String path = request.getParameter("path");

        String fileName = request.getParameter("fileName");
        // 指定要下载的文件根路径
        // 创建该文件对象
        File file = new File(path);
        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        //解决文件名中文乱码，先编码，后解码
        fileName = URLEncoder.encode(fileName, "UTF-8");


        headers.setContentDispositionFormData("attachment",fileName);
        // 定义以流的形式下载返回文件数据
        headers.setContentType(MediaType.valueOf("application/octet-stream;charset=UTF-8"));

        try {
            return new ResponseEntity<>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<byte[]>(e.getMessage().getBytes(),HttpStatus.EXPECTATION_FAILED);
        }
    }

    /**
     * 根据参数查询
     * @param query like 查询的参数
     * @param pageSize  每页数据条数
     * @param pagenum 页码
     */
    @GetMapping("/getWebFileList")
    @ResponseBody
    public PageResult<WebFile> getWebFileList(String query,Integer pageSize,Integer pagenum){

        QueryPageBean queryPageBean = new QueryPageBean(pagenum, pageSize, query);


        Integer pageTotal = webFileDao.getPageTotal(queryPageBean);



        List<WebFile> webFileList = webFileDao.getWebFileList(queryPageBean);


        return new PageResult<>(pageTotal, webFileList);
    }

    @DeleteMapping("/deleteFile/{fileId}")
    @ResponseBody
    public Result deleteFile(@PathVariable("fileId") String id){
        WebFile webFile = webFileDao.getWebFileById(id);
        try {
            webFileDao.deleteWebFile(id);
            File file = new File(webFile.getPath());
            file.delete();
            return new Result(true, "删除成功");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, "删除失败");
        }
    }
}
